import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../../widgets/image_preview.dart';
import '../../services/file_upload_service.dart';
import '../../providers/community_provider.dart';

class CommunityCreatePage extends StatefulWidget {
  const CommunityCreatePage({super.key});

  @override
  State<CommunityCreatePage> createState() => _CommunityCreatePageState();
}

class _CommunityCreatePageState extends State<CommunityCreatePage> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();
  final TextEditingController _tagController = TextEditingController();
  final ImagePicker _picker = ImagePicker();
  
  List<XFile> _selectedImages = [];
  List<String> _tags = [];
  bool _isPublishing = false;
  bool _showEditPage = false;

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _tagController.dispose();
    super.dispose();
  }

  Future<void> _pickImages() async {
    try {
      // 检查剩余可选择的图片数量
      int remainingSlots = 9 - _selectedImages.length;
      if (remainingSlots <= 0) {
        _showSnackBar('最多只能添加9张图片');
        return;
      }

      final List<XFile> images = await _picker.pickMultiImage(
        maxWidth: 1080,
        maxHeight: 1080,
        imageQuality: 80,
      );
      
      if (images.isNotEmpty) {
        setState(() {
          // 只添加剩余可容纳的图片数量
          List<XFile> imagesToAdd = images.take(remainingSlots).toList();
          _selectedImages.addAll(imagesToAdd);
          
          // 如果选择的图片超过了剩余空间，给出提示
          if (images.length > remainingSlots) {
            _showSnackBar('已添加 $remainingSlots 张图片，最多只能添加9张图片');
          }
        });
      }
    } catch (e) {
      _showSnackBar('选择图片失败: $e');
    }
  }

  Future<void> _takePhoto() async {
    try {
      // 检查是否已达到最大图片数量
      if (_selectedImages.length >= 9) {
        _showSnackBar('最多只能添加9张图片');
        return;
      }

      final XFile? image = await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1080,
        maxHeight: 1080,
        imageQuality: 80,
      );
      
      if (image != null) {
        setState(() {
          _selectedImages.add(image);
        });
        
        // 拍照成功后，询问是否继续拍照
        if (_selectedImages.length < 9) {
          _showContinuePhotoDialog();
        }
      }
    } catch (e) {
      _showSnackBar('拍照失败: $e');
    }
  }

  void _showContinuePhotoDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('拍照成功'),
          content: Text('已添加 ${_selectedImages.length}/9 张图片\n是否继续拍照？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('完成'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _takePhoto(); // 继续拍照
              },
              child: const Text('继续拍照'),
            ),
          ],
        );
      },
    );
  }

  void _addRecommendedTag(String tag) {
    setState(() {
      if (_tags.contains(tag)) {
        // 如果已选择，则删除
        _tags.remove(tag);
      } else if (_tags.length < 10) {
        // 如果未选择且未达到上限，则添加
        _tags.add(tag);
      }
    });
  }

  void _createTextPost() {
    // 创建纯文字动态，强制进入编辑页面
    setState(() {
      _selectedImages.clear(); // 确保没有图片
    });
    // 由于 build 方法中的条件是 _selectedImages.isEmpty，我们需要触发重建
    // 但这里需要一个标记来区分是否应该显示编辑页面
    _showEditPage = true;
    setState(() {});
  }

  Future<void> _publishPost() async {
    if (_titleController.text.trim().isEmpty) {
      _showSnackBar('请输入标题');
      return;
    }
    
    if (_contentController.text.trim().isEmpty) {
      _showSnackBar('请输入内容');
      return;
    }

    setState(() {
      _isPublishing = true;
    });

    try {
      List<String> imageUrls = [];
      
      // 如果有选择图片，先上传图片
      if (_selectedImages.isNotEmpty) {
        final fileUploadService = FileUploadService();
        final uploadResult = await fileUploadService.uploadImages(_selectedImages);
        
        if (uploadResult['success']) {
          imageUrls = List<String>.from(uploadResult['data']);
          _showSnackBar('图片上传成功');
        } else {
          _showSnackBar('图片上传失败: ${uploadResult['message']}');
          return;
        }
      }
      
      // 发布帖子
      final communityProvider = Provider.of<CommunityProvider>(context, listen: false);
      final success = await communityProvider.createPost(
        title: _titleController.text.trim(),
        content: _contentController.text.trim(),
        tags: _tags.isNotEmpty ? _tags : null,
        location: null, // 可以后续添加位置功能
        imageUrls: imageUrls.isNotEmpty ? imageUrls : null,
      );
      
      if (success) {
        _showSnackBar('发布成功！');
        if (mounted) {
          context.pop();
        }
      } else {
        final errorMessage = communityProvider.errorMessage ?? '发布失败';
        _showSnackBar(errorMessage);
      }
    } catch (e) {
      _showSnackBar('发布失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isPublishing = false;
        });
      }
    }
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 如果还没有选择图片且没有强制显示编辑页面，显示选择页面
    if (_selectedImages.isEmpty && !_showEditPage) {
      return _buildSelectionPage();
    }
    
    // 已选择图片或强制显示编辑页面
    return _buildEditPage();
  }

  Widget _buildSelectionPage() {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.close, color: Colors.white),
          onPressed: () => context.pop(),
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '分享你的钓鱼时光',
              style: TextStyle(
                color: Colors.white,
                fontSize: 24,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 40),
            _buildSelectionButton(
              icon: Icons.photo_library_outlined,
              title: '从相册选择',
              onTap: _pickImages,
            ),
            const SizedBox(height: 16),
            _buildSelectionButton(
              icon: Icons.camera_alt_outlined,
              title: '相机',
              onTap: _takePhoto,
            ),
            const SizedBox(height: 16),
            _buildSelectionButton(
              icon: Icons.edit_outlined,
              title: '写文字',
              onTap: _createTextPost,
            ),
            const SizedBox(height: 32),
            Container(
              width: double.infinity,
              height: 1,
              color: Colors.grey[800],
              margin: const EdgeInsets.symmetric(horizontal: 40),
            ),
            const SizedBox(height: 32),
            TextButton(
              onPressed: () => context.pop(),
              child: const Text(
                '取消',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEditPage() {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black87,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black87),
          onPressed: () {
            setState(() {
              _selectedImages.clear();
              _showEditPage = false;
            });
          },
        ),
        title: const Text(
          '发布笔记',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 图片展示
                  _buildImageDisplay(),
                  const SizedBox(height: 20),
                  
                  // 标题输入
                  _buildTitleInput(),
                  const SizedBox(height: 16),
                  
                  // 正文输入
                  _buildContentInput(),
                  const SizedBox(height: 20),
                  
                  // 推荐标签
                  _buildRecommendedTags(),
                ],
              ),
            ),
          ),
          
          // 底部操作栏
          _buildBottomActionBar(),
        ],
      ),
    );
  }

  Widget _buildSelectionButton({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 200,
        padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.1),
          borderRadius: BorderRadius.circular(25),
          border: Border.all(color: Colors.white.withOpacity(0.3)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: Colors.white, size: 24),
            const SizedBox(width: 12),
            Text(
              title,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImageDisplay() {
    if (_selectedImages.isEmpty) return const SizedBox.shrink();
    
    return Container(
      height: 200,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: Colors.grey[100],
      ),
      child: PageView.builder(
        itemCount: _selectedImages.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              // 全屏预览图片
              final imagePaths = _selectedImages.map((img) => img.path).toList();
              Navigator.of(context).push(
                MaterialPageRoute(
                  fullscreenDialog: true,
                  builder: (context) => ImagePreview(
                    imagePaths: imagePaths,
                    initialIndex: index,
                    isNetworkImage: false,
                  ),
                ),
              );
            },
            child: Stack(
              children: [
                GestureDetector(
                  onTap: () {
                    // 点击图片进行全屏预览
                    List<String> imagePaths = _selectedImages
                        .map((image) => image.path)
                        .toList();
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        fullscreenDialog: true,
                        builder: (context) => ImagePreview(
                          imagePaths: imagePaths,
                          initialIndex: index,
                          isNetworkImage: false,
                        ),
                      ),
                    );
                  },
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: Image.file(
                      File(_selectedImages[index].path),
                      width: double.infinity,
                      height: double.infinity,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Positioned(
                  top: 8,
                  right: 8,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      '${index + 1}/${_selectedImages.length}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildTitleInput() {
    return TextField(
      controller: _titleController,
      maxLength: 50,
      style: const TextStyle(
        fontSize: 18,
        fontWeight: FontWeight.w600,
        color: Colors.black87,
      ),
      decoration: InputDecoration(
        hintText: '添加标题...',
        hintStyle: TextStyle(
          fontSize: 18,
          color: Colors.grey[400],
        ),
        border: InputBorder.none,
        counterText: '',
        contentPadding: EdgeInsets.zero,
        enabledBorder: InputBorder.none,
        focusedBorder: InputBorder.none,
      ),
    );
  }

  Widget _buildContentInput() {
    return TextField(
      controller: _contentController,
      maxLines: null,
      minLines: 4,
      maxLength: 1000,
      style: const TextStyle(
        fontSize: 16,
        height: 1.5,
        color: Colors.black87,
      ),
      decoration: InputDecoration(
        hintText: '分享你的钓鱼故事...',
        hintStyle: TextStyle(
          fontSize: 16,
          color: Colors.grey[400],
        ),
        border: InputBorder.none,
        contentPadding: EdgeInsets.zero,
        enabledBorder: InputBorder.none,
        focusedBorder: InputBorder.none,
        counterStyle: TextStyle(
          color: Colors.grey[400],
          fontSize: 12,
        ),
      ),
    );
  }

  Widget _buildRecommendedTags() {
    final recommendedTags = [
      '钓鱼', '野钓', '鲤鱼', '鲫鱼', '草鱼', '技巧分享',
      '钓场推荐', '装备分享', '新手入门', '钓友交流'
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '推荐标签',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Colors.grey[800],
          ),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: recommendedTags.map((tag) {
            final isSelected = _tags.contains(tag);
            return GestureDetector(
              onTap: () => _addRecommendedTag(tag),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.blue[600] : Colors.grey[100],
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Text(
                  '#$tag',
                  style: TextStyle(
                    color: isSelected ? Colors.white : Colors.grey[700],
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }


  Widget _buildBottomActionBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: Colors.grey[200]!),
        ),
      ),
      child: SafeArea(
        child: Row(
          children: [
            // 存草稿按钮
            IconButton(
              onPressed: () {
                // TODO: 保存草稿功能
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('草稿已保存')),
                );
              },
              icon: Icon(
                Icons.drafts_outlined,
                color: Colors.grey[600],
                size: 24,
              ),
            ),
            const SizedBox(width: 12),
            
            // 发布按钮
            Expanded(
              child: ElevatedButton(
                onPressed: _isPublishing ? null : _publishPost,
                style: ElevatedButton.styleFrom(
                  backgroundColor: _isPublishing ? Colors.grey[300] : Colors.blue[600],
                  foregroundColor: Colors.white,
                  elevation: 0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25),
                  ),
                  padding: const EdgeInsets.symmetric(vertical: 14),
                ),
                child: _isPublishing
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : const Text(
                        '发布钓友圈',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }


}